/*************************************************************************
	> File Name: client.c
	> Author: yuxintao
	> Mail: 1921056015@qq.com 
	> Created Time: 2022年03月29日 星期二 09时24分56秒
 ************************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>

int serverport = 8888;
char *serverip = "192.168.223.128";
char path[100];
int sockfd = -1;
FILE* fp;

char sendbuff[1024];
char receivebuff[1024];

int running = 1;

void send_thread() {
	while (running) {
		printf("please input the path of the file:");
		fflush(stdout);
		memset(path, 0, 100);
		scanf("%s", path);
		fp = fopen(path, "r");
		if (fp == NULL) {
			perror("fopen");
			return;
		}
		while (running) {
			memset(sendbuff, 0, 1024);
			fgets(sendbuff, 1024, fp);
			if (feof(fp)) break;
			sendbuff[strlen(sendbuff)] = '$';//解决粘包问题
			send(sockfd, sendbuff, strlen(sendbuff), 0);
		}
		fclose(fp);
		memset(sendbuff, 0, 1024);
		sprintf(sendbuff, "over");
		send(sockfd, sendbuff, strlen(sendbuff), 0);
	}
}

void* receive_thread(void* arg) {
	pthread_detach(pthread_self());
	while (running) {
		memset(receivebuff, 0, 1024);
		recv(sockfd, receivebuff, 1024, 0);
		puts(receivebuff);
		fflush(stdout);
	}
	return NULL;
}

void sighandler(int sign) {
	running = 0;
	send(sockfd, "close", 4, 0);
	close(sockfd);
	exit(0);
}

int main()
{
	signal(SIGINT, sighandler);
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) {
		perror("sockfd");
		return 1;
	}
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr(serverip);
	server.sin_port = htons(serverport);
	connect(sockfd, (struct sockaddr*)&server, sizeof(struct sockaddr));

	pthread_t tid;
	pthread_create(&tid, NULL, receive_thread, NULL);
	send_thread();
	return 0;
}
